package 小测试;

import java.io.*;

/**
 * Created by Administrator on 2017/8/7.
 */
public class IO流测试 {
    public static void main(String[] args) {
        try {
            //1、文件输出
            FileWriter fileWriter = new FileWriter("D:\\a.txt",true);//true表示追加
            fileWriter.write("IO流你好");
            fileWriter.flush();//刷新缓冲区
            fileWriter.close();//关闭IO流

            //2、文件复制(一次读写1个字符)
            FileReader fileReader1 = new FileReader("a.txt");
            FileWriter fileWriter1 = new FileWriter("b.txt");
            int ch;//用来存放读取的字符
            while((ch=fileReader1.read())!=-1){
                fileWriter1.write(ch);
            }
            fileWriter1.close();
            fileReader1.close();

            //3、文件复制(一次读写1024个字符)
            FileReader fileReader2 = new FileReader("a.txt");
            FileWriter fileWriter2 = new FileWriter("b.txt");
            char[] chars = new char[1024];
            int length;
            while((length=fileReader2.read(chars))!=-1){
                fileWriter2.write(chars,0,length);//只将这一次新读取到的数据写出
            }
            fileWriter2.close();
            fileReader2.close();

            //4、文件复制(一次读写一个文本行)
            BufferedReader bufferedReader = new BufferedReader(new FileReader("a.txt"));
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("b.txt"));
            String line;
            while((line=bufferedReader.readLine())!=null){
                bufferedWriter.write(line);
                bufferedWriter.newLine();//换行
                bufferedWriter.flush();
            }
            bufferedWriter.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
